#include <pthread.h>
#include <stdio.h>

#define thread_num 1000 


static pthread_mutex_t counter_mutex  ;
 static int sum = 0;
void *thread_func(void *arg)
{   
    
    
     pthread_mutex_lock(&counter_mutex); //加锁解锁间隔越短越好 
    //printf("thread %d  start\n" ,sum); //涉及公共变量的读写操作 要放到锁内 
     sum++;
 
     pthread_mutex_unlock(&counter_mutex);
}

int main(int argc, char const *argv[])
{
    // 对一个公共变量 进行多线程的累加操作  
     pthread_mutex_init(&counter_mutex,NULL);

    
    pthread_t pthreads[thread_num];
    for (int i = 0; i < thread_num; i++)
    {
        pthread_create(&pthreads[i], NULL, thread_func, NULL);
    }

   

    for (int i = 0; i < thread_num; i++)
    {
        pthread_join(pthreads[i], NULL);
        
    }

    printf("sum 123= %d\n", sum);
    pthread_mutex_destroy(&counter_mutex);
    return 0;
}
